#!/usr/bin/perl

use strict;
use DBI;
use Time::localtime;
use XML::Simple;

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'});

my $client = "/".$CONFIG->{'directory'}."/scripts/client";
my $socket = "/".$CONFIG->{'directory'}."/".$CONFIG->{'socket'};

my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};

my ($dbh, $sth);

$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 1 }) or die "stats: Failed to connect to database\n";

my $time = `date "+%F %R"`;
chomp $time;
$time = $dbh->quote($time);


my $channels = `echo 'channels' | $client $socket`;
chomp $channels;
$channels =~ s/^\S+\s+//;
foreach my $chan (split(/\s+/, $channels)) {
	my $names = `echo 'names $chan' | $client $socket`;
	chomp $names;
	$names =~ s/^\S+\s+\S+\s+//;
	my @list = split(/\s+/, $names);
	my $num = scalar(@list);
	my $msg = join(" ", @list);

	$chan = $dbh->quote($chan);
	$msg = $dbh->quote($msg);
	$num = $dbh->quote($num);
	$dbh->do("INSERT log SET date = $time, chan = $chan, text = $msg, num = $num, type = 'stats'") or die "stats: DB stuff failed.\n";
}

$dbh->disconnect;
